package cn.itcast.controller;

import cn.itcast.entity.Result;
import cn.itcast.massage.MessageConstant;
import cn.itcast.massage.RedisMessageConstant;
import cn.itcast.pojo.Order;
import cn.itcast.service.OrderService;
import cn.itcast.utils.DateUtils;
import cn.itcast.utils.SMSUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        // 校验验证码
        // 获取前端传的验证码
        String validateCode = (String) map.get("validateCode");
        // 获取redis中的验证码
        String telephone = (String) map.get("telephone");
        String validate_code = jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_ORDER);
        if (validateCode!=null&&validate_code!=null&&validateCode.equals(validate_code)){
            // 验证码校验通过
            // 设置预约类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            try {
                // 调用service提交预约
                Result result = orderService.order(map);
                if (result.isFlag()) {
                    // 提交预约成功,发送短信给用户
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,(String) map.get("orderDate"));
                }
                return result;
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,MessageConstant.ORDER_FAIL);
            }
        }else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById4Detail(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
